﻿using System;
using System.Collections.Generic;
using System.Windows;
using Microsoft.SharePoint.Client;

namespace Shweet.Silverlight.Models
{
    public class ShweetMessage : IShweetMessage
    {
        private Web _web;
        private ListItemCollection items;
        private List<Shweet.Repository.Shweet> shweets;

        #region IShweetMessage Members

        public event EventHandler<ShweetLoadingEventArgs> ShweetLoadingComplete;
        public event EventHandler<ShweetLoadingErrorEventArgs> ShweetLoadingError;

        public void Load()
        {
            _web = ClientContext.Current.Web;
            List shweetsList = _web.Lists.GetByTitle("Shweets");
            var query = new CamlQuery();
            query.ViewXml = "<View></View>";

            items = shweetsList.GetItems(query);
            ClientContext.Current.Load(items, li => li.Include(i => i["Title"]), li => li.Include(i => i["User"]));
            ClientContext.Current.ExecuteQueryAsync(LoadShweetsSucceed, LoadShweetsFailed);
        }

        #endregion

        private void LoadShweetsSucceed(Object sender, ClientRequestSucceededEventArgs args)
        {
            if (ShweetLoadingComplete != null)
            {
                ShweetLoadingComplete(this, new ShweetLoadingEventArgs(BuildShweets()));
            }
        }

        private void LoadShweetsFailed(Object sender, ClientRequestFailedEventArgs args)
        {
            MessageBox.Show("Failed to load shweets", "Failed", MessageBoxButton.OK);
        }

        private IEnumerable<Shweet.Repository.Shweet> BuildShweets()
        {
            shweets = new List<Shweet.Repository.Shweet>();
            Shweet.Repository.Shweet shweet = null;
            foreach (ListItem currentItem in items)
            {
                shweet = new Shweet.Repository.Shweet { Text = currentItem["Title"] as string, User = currentItem["User"] as string };
                shweets.Add(shweet);
            }

            return shweets;
        }
    }
}